// pages/publish-job/publish-job.js
Page({
  data: {
    isEdit: false,
    jobId: null,
    formData: {
      title: '',
      description: '',
      jobType: 'FULL_TIME',
      location: '',
      salary: '',
      salaryType: 'MONTHLY',
      requiredWorkers: 1,
      skillRequirements: '',
      otherRequirements: '',
      workStartTime: '',
      workEndTime: ''
    },
    jobTypes: [
      { value: 'FULL_TIME', label: '全职' },
      { value: 'PART_TIME', label: '兼职' },
      { value: 'TEMPORARY', label: '临时工' },
      { value: 'INTERNSHIP', label: '实习' }
    ],
    salaryTypes: [
      { value: 'HOURLY', label: '时薪' },
      { value: 'DAILY', label: '日薪' },
      { value: 'MONTHLY', label: '月薪' }
    ],
    submitting: false
  },

  onLoad(options) {
    this.checkLoginAndRole();
    
    if (options.id && options.mode === 'edit') {
      this.setData({
        isEdit: true,
        jobId: options.id
      });
      this.loadJobDetail();
    }
  },

  // 检查登录状态和用户角色
  checkLoginAndRole() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/profile/profile'
        });
      }, 1500);
      return;
    }

    if (userInfo && userInfo.role !== 'EMPLOYER') {
      wx.showToast({
        title: '仅限用工方使用',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
  },

  // 加载岗位详情（编辑模式）
  loadJobDetail() {
    const token = wx.getStorageSync('token');

    wx.request({
      url: `http://localhost:8080/api/employer/jobs/${this.data.jobId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          const job = res.data.data;
          this.setData({
            formData: {
              title: job.title || '',
              description: job.description || '',
              jobType: job.jobType || 'FULL_TIME',
              location: job.location || '',
              salary: job.salary ? job.salary.toString() : '',
              salaryType: job.salaryType || 'MONTHLY',
              requiredWorkers: job.requiredWorkers || 1,
              skillRequirements: job.skillRequirements || '',
              otherRequirements: job.otherRequirements || '',
              workStartTime: job.workStartTime || '',
              workEndTime: job.workEndTime || ''
            }
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '加载岗位信息失败',
          icon: 'none'
        });
      }
    });
  },

  // 表单输入处理
  onFormInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 选择器变化处理
  onPickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    const options = field === 'jobType' ? this.data.jobTypes : this.data.salaryTypes;
    
    this.setData({
      [`formData.${field}`]: options[index].value
    });
  },

  // 数字输入处理
  onNumberInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = parseInt(e.detail.value) || 0;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 时间选择
  onTimeChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`formData.${field}`]: e.detail.value
    });
  },

  // 表单验证
  validateForm() {
    const { title, description, location, salary, requiredWorkers } = this.data.formData;
    
    if (!title.trim()) {
      wx.showToast({
        title: '请输入岗位标题',
        icon: 'none'
      });
      return false;
    }
    
    if (!description.trim()) {
      wx.showToast({
        title: '请输入岗位描述',
        icon: 'none'
      });
      return false;
    }
    
    if (!location.trim()) {
      wx.showToast({
        title: '请输入工作地点',
        icon: 'none'
      });
      return false;
    }
    
    if (!salary || parseFloat(salary) <= 0) {
      wx.showToast({
        title: '请输入有效薪资',
        icon: 'none'
      });
      return false;
    }
    
    if (!requiredWorkers || requiredWorkers <= 0) {
      wx.showToast({
        title: '请输入需要人数',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  },

  // 保存草稿
  saveDraft() {
    if (!this.validateForm()) return;
    this.submitJob('DRAFT');
  },

  // 发布岗位
  publishJob() {
    if (!this.validateForm()) return;
    
    wx.showModal({
      title: '确认发布',
      content: '确定要发布这个岗位吗？发布后将开始接收申请。',
      success: (res) => {
        if (res.confirm) {
          this.submitJob('PUBLISHED');
        }
      }
    });
  },

  // 提交岗位
  submitJob(status) {
    if (this.data.submitting) return;
    
    this.setData({ submitting: true });
    
    const token = wx.getStorageSync('token');
    const requestData = {
      ...this.data.formData,
      salary: parseFloat(this.data.formData.salary),
      status: status
    };
    
    const url = this.data.isEdit 
      ? `http://localhost:8080/api/employer/jobs/${this.data.jobId}`
      : 'http://localhost:8080/api/employer/jobs';
    
    const method = this.data.isEdit ? 'PUT' : 'POST';

    wx.request({
      url: url,
      method: method,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: requestData,
      success: (res) => {
        if (res.data.code === 200) {
          const message = this.data.isEdit ? '岗位更新成功' : 
                         (status === 'DRAFT' ? '草稿保存成功' : '岗位发布成功');
          wx.showToast({
            title: message,
            icon: 'success'
          });
          
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        const message = this.data.isEdit ? '岗位更新成功' : 
                       (status === 'DRAFT' ? '草稿保存成功' : '岗位发布成功');
        wx.showToast({
          title: message,
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      },
      complete: () => {
        this.setData({ submitting: false });
      }
    });
  },

  // 获取岗位类型标签
  getJobTypeLabel(value) {
    const type = this.data.jobTypes.find(t => t.value === value);
    return type ? type.label : value;
  },

  // 获取薪资类型标签
  getSalaryTypeLabel(value) {
    const type = this.data.salaryTypes.find(t => t.value === value);
    return type ? type.label : value;
  }
});
